import Taro, { redirectTo, setNavigationBarTitle } from '@tarojs/taro'
import { View, Image, Text, Camera, CoverImage, CoverView } from '@tarojs/components'
import { AtIcon, AtForm, AtButton, AtSteps } from 'taro-ui'
import React, { useState, useEffect } from 'react'

import api from '../../../utils/api'
import request from '../../../utils/request'

import './step1.less'

function AuthSteps(props) {
  const { handleNext } = props
  useEffect(() => {
    try {
      const data = Taro.getStorageSync('loginInfo')
      if (data) {
        setIdCardReverse(api.imgHost + data.id_card_reverse)
        setIdCardFront(api.imgHost + data.id_card_front)
      }
    } catch (error) {
      console.log(error)
      Taro.showToast({
        title: '获取用户信息失败',
        icon: 'none'
      })
    }
  }, [])
  const [statusItems, setStatusItems] = useState([
    { 'title': '实名认证', status: 'success' },
    { 'title': '上传身份证' },
    { 'title': '接受任务' },
    { 'title': '确认协议' }
  ])
  const [currentStep, setCurrentStep] = useState(1)
  const [idCardReverse, setIdCardReverse] = useState('')
  const [previewReversePic, setPreviewReversePic] = useState('')
  const [previewFrontPic, setPreviewFrontPic] = useState('')
  const [idCardFront, setIdCardFront] = useState('')
  const [cameraVisible, setCameraVisible] = useState(false)
  const [cameraType, setCameraType] = useState('')
  const [initStatus, setInitStatus] = useState(false)
  const idCardReverseChange = (files) => {
    console.log(files)
  }
  const selectImage = (type) => {
    setCameraVisible(true)
    setCameraType(type)
  }
  const closeCamera = () => {
    setCameraVisible(false)
  }
  const selectFromAlbum = () => {
    Taro.chooseImage({
      count: 1,
      sizeType: ['original', 'compressed'],
      sourceType: ['album']
    }).then(res => {
      setCameraVisible(false)
      Taro.showLoading({
        title: '上传图片...',
        mask: true
      })
      console.log(res.tempFilePaths[0])
      Taro.uploadFile({
        url: api.uploadUrl,
        filePath: res.tempFilePaths[0],
        name: 'file',
        header: {
          token: Taro.getStorageSync('token')
        }
      }).then(res => {
        let data = res.data
        if (typeof res.data === 'string') {
          data = JSON.parse(res.data)
        }
        return data
      }).then(res => {
        console.log(res)
        Taro.hideLoading()
        if (res.code === 0) {
          let url = res.url
          if (cameraType === 'reverse') {
            setIdCardReverse(api.imgHost + url)
            setPreviewReversePic(res.tempImagePath)
          } else {
            setIdCardFront(api.imgHost + url)
            setPreviewFrontPic(res.tempImagePath)
          }
          Taro.showToast({
            title: '上传成功',
            icon: 'none'
          })
        } else {
          Taro.showToast({
            title: res.msg,
            icon: 'none'
          })
        }
      }).catch(err => {
        console.log(err)
        Taro.showToast({
          title: '上传失败',
          icon: 'none'
        })
      })
    })
  }
  const takePhoto = () => {
    const ctx = wx.createCameraContext()
    ctx.takePhoto({
      quality: 'high'
    }).then(res => {
      setCameraVisible(false)
      Taro.showLoading({
        title: '上传图片...',
        mask: true
      })
      Taro.uploadFile({
        url: api.uploadUrl,
        filePath: res.tempImagePath,
        name: 'file',
        header: {
          token: Taro.getStorageSync('token')
        }
      }).then(res => {
        let data = res.data
        if (typeof res.data === 'string') {
          data = JSON.parse(res.data)
        }
        return data
      }).then(res => {
        Taro.hideLoading()
        if (res.code === 0) {
          let url = res.url
          if (cameraType === 'reverse') {
            setIdCardReverse(api.imgHost + url)
            setPreviewReversePic(res.tempImagePath)
          } else {
            setIdCardFront(api.imgHost + url)
            setPreviewFrontPic(res.tempImagePath)
          }
          Taro.showToast({
            title: '上传成功',
            icon: 'none'
          })
        } else {
          Taro.showToast({
            title: res.msg,
            icon: 'none'
          })
        }
      }).catch(err => {
        console.log(err)
        Taro.showToast({
          title: '上传失败',
          icon: 'none'
        })
      })
    })
  }
  const handleError = () => {
    Taro.showToast({
      title: '请授权使用摄像头',
      icon: 'none'
    })
    setCameraVisible(false)
  }
  const handleInit = () => {
    setInitStatus(true)
  }
  const onSubmit = () => {
    let data = {
      id_card_reverse: idCardReverse,
      id_card_front: idCardFront
    }
    Taro.showLoading({
      title: '身份证识别中...',
      mask: true
    })
    try {
      request(api.updateUserIdCard, 'POST', data).then((data) => {
        handleNext(2)
        Taro.hideLoading()
      }).catch(res => {
        Taro.hideToast()
        Taro.showModal({
          title: '提示',
          content: res.msg,
          showCancel: false
        })
      })
    } catch (error) {
      Taro.hideLoading()
      Taro.showToast({
        title: '提交失败'
      })
    }
  }

  return (
    <View className='ca'>
      {cameraVisible ? <Camera
        onError={handleError}
        hidden={!cameraVisible}
        onInitDone={handleInit}
        resolution="high"
        frameSize="small"
        devicePosition="back" flash="auto" className="camera">
        <CoverView hidden={!initStatus} className="controls">
          <CoverImage className="img" src={cameraType === 'front' ? '/images/card-face.png' : '/images/card-front.png'} />
          <CoverView onClick={takePhoto} className="camera-btn"></CoverView>
          <CoverView className="album" onClick={selectFromAlbum}>相册</CoverView>
          <CoverView className="back" onClick={closeCamera}>关闭</CoverView>
        </CoverView>
      </Camera> : ''}

      <View className='layout'>
        <View className='bg'></View>
        <View className='top'></View>
        <View className='cell-group group'>
          <View className="step">
            <AtSteps
              items={statusItems}
              current={currentStep}
            />
          </View>
          <AtForm>
            <View className='row'>
              <View className="title">身份证人像面</View>
              <View className="tips">仅支持1M以内JPG/JEPG/PNG格式图片 要求：画面清晰无遮挡</View>
              {
                idCardFront ? <Image onClick={selectImage.bind(this, 'front')} src={idCardFront} mode="aspectFit" className="pic"></Image> :
                  <View onClick={selectImage.bind(this, 'front')} className="pic">
                    <AtIcon value='add' size='30' color='#eee'></AtIcon>
                  </View>
              }
            </View>
            <View className='row'>
              <View className="title">身份证国徽面</View>
              <View className="tips">仅支持1M以内JPG/JEPG/PNG格式图片 要求：画面清晰无遮挡</View>
              {
                idCardReverse ? <Image onClick={selectImage.bind(this, 'reverse')} src={idCardReverse} mode="aspectFit" className="pic"></Image> :
                  <View onClick={selectImage.bind(this, 'reverse')} className="pic">
                    <AtIcon value='add' size='30' color='#eee'></AtIcon>
                  </View>
              }
            </View>
            <View className="place" style={{padding: '10px'}}></View>
          </AtForm>
        </View>
        <AtButton className='btn' circle type='primary' onClick={onSubmit}>下一步</AtButton>
      </View>
    </View>
  )
}

export default AuthSteps
